import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/base/widget/base_get_builder.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/profile/profile_bet_record/widgets/widget_bet_record_top_crypto.dart';
import 'package:flutter_09_game/pages/profile/widgets/widget_profile_rich.dart';
import 'package:flutter_09_game/pages/promotion/widgets/promotion_transfer_bing.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/formatters/decimal_input_formatter.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/appbar/common_app_bar.dart';
import 'package:flutter_09_game/widgets/btn_dropdown.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/input/common_text_field.dart';
import 'package:flutter_09_game/widgets/widget_profile_item.dart';
import 'package:flutter_09_game/widgets/widget_verification_box.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'promotion_withdraw_logic.dart';

class PromotionWithdrawPage extends StatelessWidget {
  PromotionWithdrawPage({super.key});

  final PromotionWithdrawLogic logic = Get.put(PromotionWithdrawLogic());

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<PromotionWithdrawLogic>(
        appBar: CommonAppBar(
          title: LocaleKeys.withdraw.tr,
          actions: [
            GestureDetector(
              onTap: () {
                Get.toNamed(AppRoutes.depositRecordPage);
              },
              child: AutoImage(
                Assets.commonRecordBtn,
                width: 32.w,
              ),
            ),
            12.horizontalSpace,
            GestureDetector(
              onTap: () {
                AppUserManager().showServiceSheet();
              },
              child: AutoImage(
                Assets.commonServiceBtn,
                width: 32.w,
              ),
            ),
            10.horizontalSpace,
          ],
        ),
        builder: (l) {
          // AppUserManager().user.value?.hasBindTrc20Address = false;
          // AppUserManager().user.value?.hasSetFundPassword = false;
          return Column(children: [
            // 16.verticalSpaceFromWidth,
            // "balance": 15321870000,
            // "total_recharge": 2000000173,
            // "total_rebate": 6808634500,
            // "rebate_balance": 6797634500,logic.currentWallet?.balance,logic.currentWallet?.rebateBalance
            // _buildTopDropdown(logic.getDropdownDatas(), value: value, onChanged: onChanged)

            WidgetBetRecordTopCrypto(
                backgroundColor: Colors.transparent,
                selectorTagRx: logic.selectorTagRx,
                options: logic.options),

            Expanded(
              child: Obx(() {
                int rate = logic.selectorTagRx.value.toUpperCase() == "TRX"
                    ? (logic.walletConfigRx.value.config?.withdrawLimitForTrx
                            ?.feeRate ??
                        0)
                    : (logic.walletConfigRx.value.config?.withdrawLimitForUsdt
                            ?.feeRate ??
                        0);
                return Container(
                  margin: EdgeInsets.all(16.w),
                  padding:
                      EdgeInsets.symmetric(vertical: 16.w, horizontal: 12.w),
                  decoration: BoxDecoration(
                      color: AppColor.navBgColor,
                      borderRadius: BorderRadius.circular(16.w)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildTopDropdown(logic.getDropdownDatas(),
                          value: logic.getSelectDrop()?.tag,
                          onChanged: (value) {
                        // logic.getDropdownDatas().firstWhereOrNull((item)=>item.tag == value);
                        logic.updateSelectDrop(logic
                            .getDropdownDatas()
                            .firstWhereOrNull((item) => item.tag == value));
                      }),
                      12.verticalSpaceFromWidth,
                      Text(
                        LocaleKeys.currentTransferableBalance.tr
                            .trArgs([logic.selectorTagRx.value]),
                        style: TextStyle(
                            color: AppColor.textPrimary.withOpacity(0.7),
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500),
                      ),
                      4.verticalSpaceFromWidth,
                      WidgetProfileRich(
                          text: LocaleKeys.withdrawTips1.tr.trArgs([
                        '${(logic.selectorTagRx.value.toUpperCase() == "TRX" ? logic.walletConfigRx.value.config?.withdrawLimitForTrx?.minAmount.formatWallet() : logic.walletConfigRx.value.config?.withdrawLimitForUsdt?.minAmount.formatWallet()) ?? '0.00'} ${logic.selectorTagRx.value.toUpperCase()}',
                        '${rate == 0 ? '0' : rate * 0.01}%',
                      ])),
                      4.verticalSpaceFromWidth,
                      WidgetProfileRich(
                        text: LocaleKeys.withdrawTips2.tr,
                      ),
                      4.verticalSpaceFromWidth,
                      WidgetProfileRich(
                        text: LocaleKeys.withdrawTips3.tr.trArgs([
                          logic.walletConfigRx.value.config?.withdrawTimesPerDay
                                  .toString() ??
                              '5'
                        ]),
                      ),
                      24.verticalSpaceFromWidth,
                      Expanded(
                        child: SingleChildScrollView(
                            child: (AppUserManager()
                                            .user
                                            .value
                                            ?.hasBindTrc20Address ==
                                        true &&
                                    AppUserManager()
                                            .user
                                            .value
                                            ?.hasSetFundPassword ==
                                        true)
                                ? _buildMain()
                                : const PromotionTransferBing()),
                      ),
                      12.verticalSpaceFromWidth,
                      Obx(() {
                        return Visibility(
                            visible: (AppUserManager()
                                        .user
                                        .value
                                        ?.hasBindTrc20Address ==
                                    true &&
                                AppUserManager()
                                        .user
                                        .value
                                        ?.hasSetFundPassword ==
                                    true),
                            child: CommonButton.expend(
                              title: LocaleKeys.confirm.tr,
                              enable: logic.isFormValid.value,
                              onClick: () {
                                logic.postWithdraw();
                              },
                            ));
                      })
                    ],
                  ),
                );
              }),
            ),
          ]);
        });
  }

  Widget _buildMain() {
    int rate = logic.selectorTagRx.value.toUpperCase() == "TRX"
        ? (logic.walletConfigRx.value.config?.withdrawLimitForTrx?.feeRate ?? 0)
        : (logic.walletConfigRx.value.config?.withdrawLimitForUsdt?.feeRate ??
            0);
    return Column(
      children: [
        WidgetProfileItem(
          LocaleKeys.walletAddress.tr,
          Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(vertical: 16.w, horizontal: 12.w),
              decoration: BoxDecoration(
                  color: AppColor.color2D2F35,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Obx(() {
                return Text(
                  AppUserManager()
                          .currentWalletRx
                          .value
                          .user
                          ?.withdrawAddress ??
                      '',
                  //    AppUserManager().user.value?.withdrawAddress ?? "",
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: TextStyle(
                      color: AppColor.textPrimary.withOpacity(0.3),
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500),
                );
              })),
        ),
        WidgetProfileItem(
          LocaleKeys.withdrawAmount.tr,
          CommonTextField(
            textEditingController: logic.editingController,
            backgroundColor: Colors.black.withOpacity(0.3),
            border: Border(
                bottom: BorderSide(
                    color: AppColor.textPrimary.withOpacity(0.15), width: 1.w)),
            // borderSide: BorderSide(
            //     color: AppColor.textPrimary.withOpacity(0.05), width: 1.w),
            hintText: rate == 0
                ? LocaleKeys.pleaseEnterWithdrawalAmount.tr
                : LocaleKeys.minWithdrawAmount.tr.trArgs([
                    '${(logic.selectorTagRx.value.toUpperCase() == "TRX" ? logic.walletConfigRx.value.config?.withdrawLimitForTrx?.minAmount.formatWallet() : logic.walletConfigRx.value.config?.withdrawLimitForUsdt?.minAmount.formatWallet()) ?? '0.00'} ${logic.selectorTagRx.value.toUpperCase()}',
                  ]),
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            inputFormatters: [

              FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*$')),
            ],
            onChanged: (text) {
              logic.validateForm();
            },
            rightWidget: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                AutoImage(
                  UtilsOther().getAmountTagIcon(logic.selectorTagRx.value),
                  width: 24.w,
                ),
                4.horizontalSpace,
                Text(
                  logic.selectorTagRx.value,
                  style: TextStyle(
                      color: AppColor.textPrimary.withOpacity(0.7),
                      fontSize: 14.sp),
                )
              ],
            ),
          ),
        ),
        WidgetProfileItem(
            LocaleKeys.fundPassword.tr,
            WidgetVerificationBox(
              verificationBoxController: logic.verificationBoxController,
              onValueChanged: (text) {
                logic.fundPassword.value = text;
              },
            ),
            rightWidget: GestureDetector(
              onTap: () {
                // logic.verificationBoxController.text = '';
                Get.toNamed(AppRoutes.profileFindFundPasswordPage)
                    ?.then((value) {});
              },
              child: Text(
                LocaleKeys.forgotFundPassword.tr,
                style: TextStyle(
                  color: AppColor.primary.withOpacity(0.7),
                  fontSize: 12.sp,
                ),
              ),
            )),
      ],
    );
  }

  Widget _buildTopDropdown(
    List<ModelPromotionDropdown> items, {
    required String? value,
    required Function(String) onChanged,
  }) {
    ModelPromotionDropdown? dropdown = logic.getSelectDrop();
    return BtnDropdown(
      items: const [],
      customStyle: items,
      value: value,
      // width: 1.sw - 32.w,
      // mainAxisAlignment: MainAxisAlignment.start,
      onChanged: (value) {
        onChanged.call(value);
      },
      width: 319.w,
      child: Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.w),
          decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              borderRadius: BorderRadius.circular(8.w),
              border: Border(
                  bottom: BorderSide(
                      color: AppColor.textPrimary.withOpacity(0.15),
                      width: 1.w))),
          child: Row(
            children: [
              Text(
                dropdown?.title ?? "",
                // textAlign: TextAlign.center,
                style: TextStyle(
                  fontFamily: 'PingFang SC',
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  color: AppColor.textPrimary.withOpacity(0.94),
                ),
              ),
              const Spacer(),
              AutoImage(
                UtilsOther().getAmountTagIcon(dropdown?.symbol),
                width: 20.w,
              ).marginOnly(right: 4.w),
              Text(
                dropdown?.balance.formatWallet() ?? '',
                // textAlign: TextAlign.center,
                style: TextStyle(
                  fontFamily: 'PingFang SC',
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w900,
                  color: AppColor.textPrimary.withOpacity(0.94),
                ),
              ),
              4.horizontalSpace,
              AutoImage(
                Assets.promotionCommissionCaretDown,
                width: 16.w,
              )
            ],
          )),
      // child: Container(
      //   padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 12.w),
      //   decoration: BoxDecoration(
      //       border: Border(
      //           bottom: BorderSide(
      //               color: AppColor.textPrimary.withOpacity(0.15), width: 1)),
      //       color: Colors.black.withOpacity(0.3),
      //       borderRadius: BorderRadius.circular(8.w)),
      //   child: Row(
      //     children: [
      //       Expanded(
      //           child: Text(
      //             value,
      //             style: TextStyle(
      //               fontSize: 14.sp,
      //               fontWeight: FontWeight.w900,
      //               color: btnColor ?? AppColor.textPrimary.withOpacity(0.94),
      //             ),
      //           )),
      //       AutoImage(
      //         Assets.promotionCommissionCaretDown,
      //         width: 16.w,
      //       )
      //     ],
      //   ),
      // )
    );
  }
}
